import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Button, message, Row, Select, Spin } from 'antd';
import { Ref, useEffect, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import React from 'react';
import '../../../../../public/js/LodopFuncs.js';
import { getPrinterAssetUrl } from '@/services/urlconst';

export const PrintBarcode = React.forwardRef<any, any>(({ onClose, modalTitle, modalWidth = 0.25, searchParams, selectRowKeys }, ref) => {
  /**
   * modal ref
   */
  const printBarcodeModalRef: Ref<IOneModalRef> = useRef(null);

  /** 打印机列表 */
  const [printOption, setPrintOption] = useState<Record<string, any>[]>([]);

  /** 设置打印机loding */
  const [loading, setLoading] = useState(false);

  /** 表单 form */
  const [assetTypeForm] = Form.useForm();

  useEffect(() => {
    if (window['LODOP'] == undefined) {
      message.warning('请检查是否安装或启动打印控件！');
      onClose && onClose();
      return;
    }

    setLoading(true);
    // 获取打印机list
    let iPrinterCount = window['LODOP'].GET_PRINTER_COUNT();
    let arr: any = [];
    for (let i = 0; i < iPrinterCount; i++) {
      // 获取打印机名称 (目前只要名称为'Honeywell'的打印机)
      let label = window['LODOP'].GET_PRINTER_NAME(i);
      if (label.indexOf('Honeywell') >= 0) {
        arr.push({ label: label, value: i });
      }
    }
    setPrintOption(arr);

    /** 初始化默认上次选择 */
    let PrinterCode = localStorage.getItem('PrinterCode');
    if (PrinterCode && !isNaN(Number(PrinterCode)) && arr.length != 0) {
      let isExist = arr.some((v) => v.value == PrinterCode);
      if (isExist) assetTypeForm.setFieldValue('printerValue', Number(PrinterCode));
    } else {
      assetTypeForm.setFieldValue('printerValue', arr.length > 0 ? arr[0].value : undefined);
    }

    /** 更新设置打印机 */
    updataPrinter();
  }, []);

  /** 更新设置打印机 */
  const updataPrinter = (value = undefined) => {
    let CLODOP = window['getCLodop']();

    window['LODOP'].PRINT_INIT('');
    let printerValue = 0;
    if (value == undefined) {
      printerValue = assetTypeForm.getFieldValue('printerValue');
    } else printerValue = value;

    if (printerValue == undefined) {
      message.warning('当前不存在可用打印机！');
      setLoading(false);
      return;
    }

    if (window['LODOP'].CVERSION) {
      CLODOP.On_Return = function (TaskID, Value) {
        if (value == undefined) return setLoading(false);
        if (Value == 'ok') {
          message.success('设置成功');
          localStorage.setItem('PrinterCode', printerValue.toString());
        } else {
          message.success('设置失败，请重试！');
        }
        setLoading(false);
      };
    }

    var strResult = window['LODOP'].SET_PRINT_MODE('WINDOW_DEFPRINTER', printerValue);
    if (!window['LODOP'].CVERSION) alert(strResult);
  };

  /** 切换 打印机 */
  const selectChange = async (value) => {
    setLoading(true);
    await updataPrinter(value);
  };

  /**
   * 关闭弹窗
   */
  const onCencal = () => {
    if (printBarcodeModalRef) {
      if (printBarcodeModalRef.current) {
        if (printBarcodeModalRef.current.onModalCancel) {
          assetTypeForm.setFieldsValue({});
          printBarcodeModalRef.current.onModalCancel();
        }
      }
    }
  };

  /**
   * 保存
   */
  const onSave = () => {
    let printerValue = assetTypeForm.getFieldValue('printerValue');
    if (printerValue == undefined) {
      message.warning('当前不存在可用打印机！');
      return;
    }
    // return;
    message.success('打印中，请稍后...');
    setLoading(true);
    let valList = selectRowKeys?.valList;
    for (let i = 0; i < valList.length; i++) {
      // 初始化运行环境，清理异常打印遗留的系统资源，设定打印任务名
      window['LODOP'].PRINT_INIT(valList[i].assetCode);

      // 设定打印纸张为固定纸张或自适应内容高，并设定相关大小值或纸张名及打印方向
      window['LODOP'].SET_PRINT_PAGESIZE(0, '90mm', '70mm', 'honeywell');

      // 增加图片打印项，设定该打印项在纸张内的位置和区域大小
      window['LODOP'].ADD_PRINT_IMAGE(20, 30, '90mm', '70mm', `${getPrinterAssetUrl()}${valList[i].barCodeUrl}`);

      // 不经打印预览的直接打印【打印机开始实际打印，返回逻辑结果，正确打印时返回真，打印出错时返回假】
      window['LODOP'].PRINT();
    }
    setLoading(false);
    onCencal();
  };

  const customFooter = (
    <>
      <Button onClick={onCencal}>取消</Button>
      <Button type="primary" onClick={onSave}>
        打印
      </Button>
    </>
  );

  return (
    <>
      <OneModal
        open={true}
        ref={printBarcodeModalRef}
        title={modalTitle}
        width={document.body.clientWidth * modalWidth}
        onCancel={onClose}
        bodyStyle={{ padding: '5px 0px' }}
        centered
        footer={customFooter}
      >
        <Spin spinning={loading}>
          <div className={pageStyles['fromView-styles']}>
            <Form form={assetTypeForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label={'选择打印机'}
                    name={'printerValue'}
                    rules={[
                      {
                        required: true,
                        message: `请选择打印机`,
                      },
                    ]}
                  >
                    <Select placeholder={`请选择打印机`} onChange={selectChange}>
                      {printOption?.map((item: any) => {
                        return (
                          <Select.Option key={item?.value} value={item?.value}>
                            {item?.label}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
});
